//
//  BNDOfficeDocDetailsWebVc.m
//  OfficeDoc
//
//  Created by pie on 2022/4/4.
//  Copyright © 2022 pie. All rights reserved.
//

#import "BNDOfficeDocDetailsWebVc.h"
#import "LCActionSheet.h"
#import <WebKit/WebKit.h>
#import "LVDownLoadManager.h"
#import <WebKit/WebKit.h>
#import "ReminderHUD.h"
#import "BNDOfficeDocKit.h"

@interface BNDOfficeDocDetailsWebVc ()<WKNavigationDelegate,WKUIDelegate, UIScrollViewDelegate,UIDocumentInteractionControllerDelegate>
@property (nonatomic, strong) WKWebView  *webView;
@property (nonatomic, strong) UIButton    *rightBarButtonItem;

@property (copy, nonatomic)  NSString *urlString; //链接

@property (strong, nonatomic)  LVDownLoadManager *downLoadManager; //链接
@property (strong, nonatomic)  UIDocumentInteractionController * documentController;
@end

@implementation BNDOfficeDocDetailsWebVc

- (void)dealloc
{
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view addSubview:self.webView];
}

- (void)loadDataMethod:(NSString*)url withState:(BNDWebState)state;
{
    if(state == BndWebStateNDownload){
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightBarButtonItem];
    }
    self.urlString = url;
    
    [self handleDownLoadManager:0];
    
    
    //    NSURL *weburl = [NSURL URLWithString:url];
    //    NSURLRequest *request;
    //    request = [NSURLRequest requestWithURL:weburl];
    //    [self.webView loadRequest:request];
}

- (void)moreItemButton
{
    @weakify(self)
    LCActionSheet *sheet = [LCActionSheet sheetWithTitle:nil cancelButtonTitle:@"取消" clicked:^(LCActionSheet * _Nonnull actionSheet, NSInteger buttonIndex) {
        @strongify(self)
        [self handleDownLoadManager:1];
    } otherButtonTitles:@"保存文件", nil];
    [sheet show];
}

- (void)handleDownLoadManager:(NSInteger)type
{
    
    _downLoadManager = [LVDownLoadManager managerWithName:[NSString stringWithFormat:@"BNDOFFICDOC%@",[BNDPreference sharedInstance].openId]];
  __block LVDownLoadInfo *info = [_downLoadManager downloadInfoForURL:self.urlString];
    if(info == nil){
        info = [_downLoadManager creatDownloadTask:self.urlString name:_info[@"fileName"] progress:^(unsigned long long totalBytesWritten, unsigned long long totalBytesExpectedToWrite) {
            
        } state:^(LVDownloadState state, NSString *file, NSError *error) {
            
            
        }];
        
        [info setProgressChangeBlock:^(unsigned long long totalBytesWritten, unsigned long long totalBytesExpectedToWrite) {
            CGFloat  progressData  = ((float)totalBytesExpectedToWrite/totalBytesWritten);
            if (progressData > 0) {
                BND_dispatch_main_async_safe(^{
                    [ReminderHUD showProgress:progressData status:@"加载中"];
                })
            }
        }];
        @weakify(self)
        [info setStateChangeBlock:^(LVDownloadState state, NSString *file, NSError *error) {
            @strongify(self)
            if(state == LVDownloadStatedownLoadCompleted){
                [ReminderHUD disappear];
                // [ReminderHUD showReminderText:@"下载成功" delayTime:1.0];
                if(type ==1){
                    [self handleDocumentController:file and:self.info[@"fileName"]];
                }else{
                    NSURL *fileURL = [NSURL fileURLWithPath:file];
                    NSURL *accessURL = [fileURL URLByDeletingLastPathComponent];
                    [self.webView loadFileURL:fileURL allowingReadAccessToURL:accessURL];
                }
            }else{
                [ReminderHUD showReminderText:@"加载失败" delayTime:1.0];
            }
        }];
    }else{
        if(type ==1){
            [self handleDocumentController:info.downLoadingPath and:_info[@"fileName"]];
        }else{
            NSURL *fileURL = [NSURL fileURLWithPath:info.downLoadingPath];
            NSURL *accessURL = [fileURL URLByDeletingLastPathComponent];
            self.urlString = info.downLoadingPath;
            [self.webView loadFileURL:fileURL allowingReadAccessToURL:accessURL];
        }
        
    }
    
}


- (void)handleDocumentController:(NSString *)fileURL and:(NSString*)fileName
{
    self.documentController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"file://\%@",fileURL]]];
    self.documentController.name = fileName;
    self.documentController.delegate = self;
    self.documentController.UTI = @"com.qqkj.mjpark";
    //    self.documentController.modalPresentationStyle = UIModalPresentationFullScreen;
    [self.documentController presentOpenInMenuFromRect:CGRectZero  inView:[BNDPushVCHandler topViewController].view animated:YES];
}

#pragma mark --UIDocumentInteractionControllerDelegate--

- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)interactionController
{
    return [BNDPushVCHandler topViewController];
}

-(UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller
{
    return [BNDPushVCHandler topViewController].view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller
{
    return [BNDPushVCHandler topViewController].view.frame;
}


#pragma mark - Get

- (UIButton *)rightBarButtonItem
{
    if (_rightBarButtonItem == nil) {
        _rightBarButtonItem = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightBarButtonItem.titleLabel.font = BNDPFRegularFont(15);
        [_rightBarButtonItem setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -20)];
        [_rightBarButtonItem lk_setImage:BNDImageNamed(@"bnd_top_icons_more_dark")];
        [_rightBarButtonItem addTarget:self action:@selector(moreItemButton) forControlEvents:UIControlEventTouchUpInside];
        [_rightBarButtonItem setFrame:CGRectMake(0, 0, 44, 44)];
    }
    
    return _rightBarButtonItem;
}

- (WKWebView *)webView
{
    if (!_webView) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        config.allowsInlineMediaPlayback = YES;
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, BNDNavigationBarHeight(), kDeviceWidth, kDeviceHeight-BNDNavigationBarHeight()) configuration:config];
        [_webView.scrollView setDelegate:self];
        [_webView setUIDelegate:self];
        [_webView setNavigationDelegate:self];
        [_webView.scrollView setMinimumZoomScale:1.0f];
        [_webView.scrollView setMaximumZoomScale:1.0f];
        _webView.backgroundColor = [UIColor whiteColor];
        [_webView setOpaque:NO];
        if (@available(iOS 11.0, *)) {
            _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    
    return _webView;
}

#pragma mark - Delegate

// 页面准备加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"------页面准备加载时调用");
}
// 页面内容开始加载
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    NSLog(@"------页面内容开始加载");
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"------页面,%@",error);
    //    if (error.code = 102) {
    //        [webView reload];
    //    }
}
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"------页面,%@",error);
}
// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{

//    NSLog(@"%@",navigationResponse.response.URL.absoluteString);
//    NSString *urlString = self.urlString;
//    NSData *data = [NSData dataWithContentsOfURL:navigationResponse.response.URL];
//    NSURL *weburl = [NSURL URLWithString:urlString];
//    WS(weakSelf)
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
////        NSData *data = [NSData dataWithContentsOfURL:weburl];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [weakSelf.webView loadData:data MIMEType:@"application/vnd.openxmlformats-officedocument.presentationml.presentation" characterEncodingName:@"UTF-8" baseURL:weburl];
//        });
//    });
    
    //    [self.webView loadData:data MIMEType:@"application/vnd.openxmlformats-officedocument.presentationml.presentation" characterEncodingName:@"UTF-8" baseURL:weburl];

    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}
// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSLog(@"%@",navigationAction.request.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
    //不允许跳转
    //    decisionHandler(WKNavigationActionPolicyCancel);
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    // 禁用用户选择
    [self.webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';"completionHandler:nil];
    [self.webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:nil];
}


@end
